/**
 * Created by bianlian on 16/9/19.
 */

import React, { Component, PropTypes } from 'react';
import { StyleSheet, View, Image, TouchableOpacity, Platform, BackAndroid } from 'react-native';
import { MtContainer, MtListView, MtSeparator, MtChar,MtNavBar, MtScreen, MtEmptyView, MtColor,MtButton, MtLoadingModal, MtLabelBar } from 'martian-ui';
const { MtT1, MtLabel, MtL3, MtT3 } = MtChar;
import {fetchDeviceInfo, UpdateDeviceInfo} from '../action/girlAction';
import { bindActionCreators } from 'redux';
import {connect} from 'react-redux';
const EntityLabels = require('../constants/entities');
import values from 'lodash/values';
import keys from 'lodash/keys';
import assign from 'lodash/assign';
import DropDownModal from '../components/DropDownModal';
import ConditionButton from '../components/ConditionButton';
const { width, height } = MtScreen;
import AddSence from './AddSence'
import AllScence from './AllScence'
import { fetchScenesInfo, fetchRoomList} from '../action/girlAction';
import NavigationBar from '../components/common/NavigationBar'
import LabelBar from '../components/common/ArgraceUI/LabelBar'
const MtIcon = require('martian-icon');
const YaguanRoomDeviceListCell = require('../components/YaguanRoomDeviceListCell');
const YaguanRoomScenceListCell = require('../components/YaguanRoomScenceListCell');
function _renderRow(deviceId, sectionID, rowID) {
    const { navigator, UpdateDeviceInfo, name } = this.props;
    return (
        <YaguanRoomDeviceListCell
            navigator={navigator}
            deviceId={deviceId}
            roomName={name}

        />
    );
}

function _renderRow1(scenceId, sectionID, rowID) {
    const { navigator } = this.props;
    return (
        <YaguanRoomScenceListCell
            navigator={navigator}
            scenceId={scenceId}

        />
    );
}

class YaguanRoomDevices extends Component {

    // 构造
    constructor(props) {
        super(props);
        this.deviceControlWithParams = this.deviceControlWithParams.bind(this);
        this.state={
            Show: false,
            senceActions:[{id: 1, name:'新增场景'}, {id: 2, name:'编辑场景'}]
        }
    }

    /**
     * 调用数据 :
     *      1. 当触发Action方法请求数据反馈到Reducer中
     *      2. Reducer通过ActionType判断该更新哪个UI中的State
     *      3. 最后刷新界面显示数据
     */
    componentWillMount() {
		this.convertPropsToStates(this.props);
        if (Platform.OS === 'android') {
            BackAndroid.addEventListener('hardwareBackPress', () => this.onBackAndroid());
        }
    }

    deviceControlWithParams(param) {
        // var RNAlibcSdk = NativeModules.RNAlibcSdk;
        // console.warn(JSON.stringify(RNAlibcSdk));
        // console.warn(JSON.stringify(param)+'dddd');
        // RNAlibcSdk.deviceControlWithParams(param, (err, info) => {
        //         if (!err)
        //             console.log(info)
        //         else
        //             console.log(err)
        //     }
        // );
    }

    componentDidMount() {
        // setTimeout(() => {
        //     this.setState({
        //         Show: false
        //     });
        // }, 3)
		    this.refresh();
        if (Platform.OS === 'android') {
            BackAndroid.addEventListener('hardwareBackPress', () => this.onBackAndroid());
        }

    }
    refresh(){
      const {fetchScenesInfo, gatewayId} = this.props;
        console.warn('gatewayId'+gatewayId)
      fetchScenesInfo(gatewayId);
    }
    refreshDevice(){
      const {houseId, fetchRoomList} = this.props;
      fetchRoomList(houseId);
    }
    convertPropsToStates(props) {
      const { devicesEntities, scenesEntities, deviceIds, roomId } = props;

      let newDeviceIds =[];
      if (devicesEntities && keys(devicesEntities).length > 0) {
          newDeviceIds = deviceIds.map((list) => {
              return devicesEntities[list];
          }
        ).filter(ele => ele.productKey !== null && ele.deviceName !== null).map(ele => ele.deviceId);
      }

      const scenesIds = scenesEntities && values(scenesEntities).filter(ele => ele.roomId === roomId).sort((ele1, ele2) => {
          return ele1['inRoomSort'] - ele2['inRoomSort'];
      }).map(ele =>ele.id);
      const newState = assign({
        scenesIds,
        newDeviceIds,
      });

      if (newState) {
        this.setState(newState);
      }
    }
    componentWillReceiveProps(nextProps) {
      this.convertPropsToStates((nextProps));
    }
    /**
     * 监听Android返回按键
     * @returns {boolean}
     */
    onBackAndroid() {
        const {navigator} = this.props;
        if (navigator.getCurrentRoutes().length > 1) {
            navigator.pop();
            return true;
        }
        //退出
        return false;

    }
    render() {
        const { name, isFetching, navigator, roomId,  gatewayId } = this.props;
		    const { newDeviceIds, scenesIds, senceActions } = this.state;
        const rightButton = <ConditionButton
                                ref={(button) => {
                                        this.sdtBtn = button;
                                    }
                                }
                                title={'操作'}
                                checked={senceActions}
                                onSelect={(selected) => {
                                    onClose(this, 5);
                                    if (selected) {
                                        //this.getRelationSdt();
                                        this.sdtModal.open();
                                    }
                                    else {
                                        this.sdtModal.close();
                                    }
                                }}
                            />
        const renderRowBind = _renderRow.bind(this);
        const renderRowBind1 = _renderRow1.bind(this);

        // 设备
        let deviceList;
        if (newDeviceIds && newDeviceIds.length > 0) {
          deviceList = (
                <MtListView
                    data={newDeviceIds}
                    renderRow={renderRowBind}
                    initialListSize={10}
                    scrollRenderAheadDistance={500}
                    onEndReachedThreshold={10}
                    renderSeparator={undefined}
                    enableEmptySections={true}
                    contentContainerStyle={styles.listViewStyle}
                    removeClippedSubviews={false}
                    onRefresh={() => {
                        this.refreshDevice();
                    }}
                    onEndReached={() => {

                    }}
                    refreshing={isFetching}
                />
            );
        }
        else {
          deviceList = null
        }

        //房间场景
        let roomScene;
        if (scenesIds && scenesIds.length > 0) {
          roomScene = (
                <MtListView
                    data={scenesIds}
                    renderRow={renderRowBind1}
                    initialListSize={10}
                    horizontal = {true}
                    scrollRenderAheadDistance={500}
                    onEndReachedThreshold={10}
                    renderSeparator={undefined}
                    enableEmptySections={true}
                    contentContainerStyle={styles.listViewStyle}
                    removeClippedSubviews={false}
                    onRefresh={() => {
                        this.refresh();
                    }}
                    onEndReached={() => {

                    }}
                    refreshing={isFetching}
                    style={{height: 300}}
                />
            );
        }
        else {
          roomScene = null
        }
        console.warn('scenesIds'+ JSON.stringify(scenesIds))
        return (
            <MtContainer>
                <Image source={require('../img/bg.png')} style={styles.bgImage} />
                <MtLoadingModal
                    visible={false}
                    tip="加载设备"
                />
                <NavigationBar
                    title={name}
                    statusBar={{backgroundColor: '#ECEAE7', barStyle: 'dark-content'}}
                    navigator={navigator}
                    rightButton={rightButton}
                    style={{backgroundColor: 'transparent'}}
                />
                {scenesIds && scenesIds.length > 0 &&
                  <LabelBar
                      onPress={() => {
                          navigator.push({
                              component: AllScence,
                              params: {
                                  roomId: roomId,
                                  navigator: navigator,
                                  gatewayId
                              }
                          })
                      }}
                      title="房间场景"
                      containerStyle={{backgroundColor: 'transparent'}}
                      titleStyle={{fontSize: 14, color: '#333333', fontWeight: 'bold'}}
                  />
                }
                {roomScene}
                <LabelBar
                      onPress={() => {
                          navigator.push({
                              component: AllScence,
                              params: {
                                  roomId: roomId,
                                  navigator: navigator,
                                  gatewayId
                              }
                          })
                      }}
                      title="房间设备"
                      containerStyle={{backgroundColor: 'transparent'}}
                      titleStyle={{fontSize: 14, color: '#333333', fontWeight: 'bold'}}
                  />
                {deviceList}

                <DropDownModal
                    key="sdtModal"
                    marginLeft={width/3 * 2}
                    marginTopHeight={MtNavBar.height}
                    ref={(modal) => {
                        this.sdtModal = modal;
                    }}
                    onSelect={
                      (item) => {
                        onClose(this, 6);
                        if(item.id = 1){
                          navigator.push({
                            component: AddSence,
                            params: {
                              roomId: this.props.roomId,
                              gatewayId: this.props.gatewayId,
                            }
                          })
                        }

                      }
                    }
                    onClosed={()=>{
                        console.warn(1)
                    }}
                    options={senceActions}
                    transformOption={option => option.name}
                    testOptionEqual={(a, b) => a.id === b.id}
                />
            </MtContainer>
        );
    };
}
function onClose(me, idx) {
    if (idx !== 5) {
        me.sdtBtn.clean();
        me.sdtModal.close();
    }
}
function mappingStateToProps(state, ownProps) {
    const entities= state['entities'];
    const devicesEntities = entities[EntityLabels.devices];
    const scenesEntities = entities[EntityLabels.scenes];
    const assessTokenEntity = entities[EntityLabels.token];
    const assessToken = assessTokenEntity && values(assessTokenEntity)[0].assessToken

    return {
        devicesEntities,
        scenesEntities,
        assessToken
    };
}
function mapDispatchToProps(dispatch) {
    const actions = {
        fetchScenesInfo,
        fetchRoomList
    };
    return bindActionCreators(actions, dispatch);
}

export default connect(mappingStateToProps, mapDispatchToProps)(YaguanRoomDevices);

const styles = StyleSheet.create({
    bgImage: {
      width: width,
      height: height,
      position: 'absolute',
      top: 0,
      left: 0,
      right: 0,
      bottom: 0,
    },
    subtitle:{
        fontWeight: 'bold',
        paddingHorizontal:15,
        paddingTop:10,
        marginLeft: 12,
        alignItems:'center', // 必须设置,否则换行不起作用
    },
    listViewStyle:{
        // 改变主轴的方向
        flexDirection:'row',
        // 多行显示
        flexWrap:'wrap',
        // 侧轴方向
        alignItems:'center', // 必须设置,否则换行不起作用
    },
    textRight: {
        textAlign: 'right',
    },
});
